package netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class CloseFutureClient {
    static Logger logger = LogManager.getLogger("mylog");
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new LoggingHandler())
                                .addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        channelFuture.sync();
        Channel channel = channelFuture.channel();
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
           while (true) {
               String s = scanner.nextLine();
               if ("q".equals(s)) {
                   channel.close();
                   break;
               }
               channel.writeAndFlush(s);
           }
        }, "input").start();
        ChannelFuture closeFuture = channel.closeFuture();
      /*  System.out.println("waiting close");
        closeFuture.sync();
        logger.debug("closed"); */

        closeFuture.addListener((ChannelFutureListener) futureListener-> {
           // public void operationComplete(ChannelFuture channelFuture)  {
                logger.debug("closed");
                group.shutdownGracefully();
           // }
        });
    }
}
